package site.teamo.biu.net.common.web.interceptor;


import cn.hutool.core.util.StrUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import site.teamo.biu.net.common.constant.HttpHeader;
import site.teamo.biu.net.common.web.configuration.PassportConfiguration;
import site.teamo.biu.net.common.web.constant.ResponseCode;
import site.teamo.biu.tool.core.cache.SessionCache;

@Component
public class UserInterceptor implements HandlerInterceptor {

    @Resource
    private SessionCache<String> sessionCache;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader(HttpHeader.ACCESS_TOKEN);
        if (StrUtil.equals(PassportConfiguration.USERNAME, sessionCache.isLogin(token))) {
            return true;
        }
        request.setAttribute("responseCode", ResponseCode.AUTHENTICATION_FAILED_ERROR);
        request.getRequestDispatcher("/exception").forward(request, response);
        return false;
    }
}